import { IProfile } from './../reducer/user';
import { getProfileAPI, updatePhotoAPI, updateProfileAPI } from './../../api/user';
import { AppDispatch } from './../index';
import { loginAPI } from '@/api/login';
import { getUserInfoAPI } from '@/api/user';
import { setAuth } from '@/utils/storage';
import { Toast } from 'antd-mobile';

export const loginAction = (mobile: string, code: string) => {
  return async () => {
    const res = await loginAPI(mobile, code);
    setAuth(res.data);
    Toast.show({
      content: '登录成功',
    });
  };
};
export const getUserInfoAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getUserInfoAPI();
    dispatch({ type: 'user/saveUserInfo', payload: res.data });
  };
};

export const getProfileAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getProfileAPI();
    dispatch({ type: 'user/saveProfile', payload: res.data });
  };
};

export const updatePhotoAction = (file: File) => {
  const formData = new FormData();
  formData.append('photo', file);

  return async (dispatch: AppDispatch) => {
    const res = await updatePhotoAPI(formData);
    console.log('res  ----->  ', res);
  };
};

export const updateProfileAction = (data: Partial<IProfile>) => {
  return async (dispatch: AppDispatch) => {
    await updateProfileAPI(data);
  };
};
